package com.ll.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.util.UuidUtils;
import com.ll.common.constant.AuthConstant;
import com.ll.common.constant.AuthServerConstant;
import com.ll.common.exception.BizCodeEnume;
import com.ll.common.utils.R;
import com.ll.common.vo.MemberEntityVo;
import com.ll.gulimall.authserver.feign.MemberFeignService;
import com.ll.gulimall.authserver.feign.SMSFeginService;
import com.ll.gulimall.authserver.vo.UserLoginVo;
import com.ll.gulimall.authserver.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;


import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 21243
 */
@Controller
public class LoginController {

    @Autowired
    SMSFeginService smsFeginService;


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送验证码
     *
     * @param phone 手机号
     * @return
     */
    @RequestMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {

        //TODO 接口防刷
        String reidsCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_KEY + phone);
        //随机验证码
        String code = UuidUtils.generateUuid().substring(0, 5);
        if (!StringUtils.isEmpty(reidsCode)) {
            // 用户在60s发送多次 
            String[] str = reidsCode.split("_");
            //拆分验证码 查看用户是否在60s发送多次
            if (System.currentTimeMillis() - Long.parseLong(str[1]) < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }

        }
        //存入验证码 有效期5分钟
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_KEY + phone, code + "_" + System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        smsFeginService.sendCode(phone, code);
        return R.ok();

    }


    /**
     * RedirectAttributes redirectAttributes重定向存值 原理 session cookie
     * TODO 分布式该怎么处理呢
     *
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            //JSR发现错误
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            //重定向到r注册
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //校验验证码是否正确
        String reidsCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_KEY + vo.getPhone());
        if (StringUtils.isEmpty(reidsCode)) {
            //验证码过期或者失效
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码过期");
            redirectAttributes.addFlashAttribute("errors", errors);
            //重定向到r注册
            return "redirect:http://auth.gulimall.com/reg.html";
        } else {
            if (!vo.getCode().equalsIgnoreCase(reidsCode.split("_")[0])) {
                //验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                //重定向到r注册
                return "redirect:http://auth.gulimall.com/reg.html";
            } else {
                //验证码正确 开始调用会员服务注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    //验证码 验证成功删除验证码
                    redisTemplate.delete(AuthConstant.SMS_CODE_KEY + vo.getPhone());
                    //远程调用成功 跳转登录页面
                    //注册成功
                    return "redirect:http://auth.gulimall.com/";
                }
                if (r.getCode() == BizCodeEnume.USER_EXIST_EXCEPTION.getCode()) {
                    //用户名存在
                    Map<String, String> errors = new HashMap<>();
                    errors.put("userMsg", r.get("msg").toString());
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
                if (r.getCode() == BizCodeEnume.PHONE_EXIST_EXCEPTION.getCode()) {
                    //手机号存在
                    Map<String, String> errors = new HashMap<>();
                    errors.put("phoneMsg", r.get("msg").toString());
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
                return "redirect:http://auth.gulimall.com/";
            }
        }

    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object user = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (user != null) {
            //用户会话未过期 返回首页
            return "redirect:http://gulimall.com";
        } else {
            //会话过期返回登录
            return "login";
        }

    }


    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(loginVo);
        if (r.getCode() == 0) {
            //登录成功
            MemberEntityVo memberEntity = r.getData(new TypeReference<MemberEntityVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, memberEntity);
            return "redirect:http://gulimall.com";
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg", r.get("msg").toString());
        redirectAttributes.addFlashAttribute("errors", errors);
        //登录失败
        return "redirect:http://auth.gulimall.com/";
    }
}
